<?php
/**
 * @author Administrator
 * @date 2022/9/26 20:13
 * @desciption:
 */

namespace Plugins;

use Closure;

class LoadApps
{
    private $app = null;

    /**
     * @var array
     */
    private $bindApps = [
        \JsonApi\Application::class
    ];

    public function __construct()
    {
        $this->app = app();
        $this->loadStaticApps($this->app);
        $app_path = $this->app->basePath() . DIRECTORY_SEPARATOR . Application::$app_path;
        $this->loadDynamicApps($this->app,$app_path);
    }

    private function loadDynamicApps($app,$app_path){
        if(is_dir($app_path)){
            $arr = scandir($app_path);
            if(is_array($arr)){
                foreach ($arr as $item){
                    if($item != "." && $item != ".." && is_dir($app_path . DIRECTORY_SEPARATOR . $item)){
                        // 命名空间：Plugins\{$item}\Application
                        $class = $this->buildNameSpace($item);
                        if(class_exists($class) && method_exists($class,"boot")){
                            //通过定义公共方法进行禁用app
                            if(function_exists("app_is_disable") && app_is_disable($class)){
                                continue;
                            }
                            $class::boot($app);
                        }
                    }
                }
            }
        }
    }

    private function loadStaticApps($app){
        if(!empty($this->bindApps)){
            foreach($this->bindApps AS $apps){
                if(method_exists($apps,"boot")){
                    $apps::boot($app);
                }
            }
        }
    }

    private function buildNameSpace($app_name){
        return "\Plugins\\" . $app_name . "\\" . "Application";
    }

    public function handle($request, Closure $next)
    {
        return $next($request);
    }
}